package com.yunfinal.api.tpl.json;

import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.jfinal.handler.Handler;
import com.jfinal.log.Log;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 对 /sql/ 下的 JF文件做定向到 TplController中
 */
public class ApiHandler extends Handler {
    private static final Log log = Log.getLog(ApiHandler.class);
    public static String getName(Controller c){
        return c.getAttr(nameKey);
    }

    private static final String prefix_data ="/api/data/";
    private static final String nameKey = "ApiHandler_name";

    @Override
    public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
        if (target.indexOf('.') > 0) {
            return;
        }
        //拦截JF模板渲染
        if (target.startsWith(prefix_data)){
            setName(request, target, prefix_data);
            target = prefix_data;
        }
        next.handle(target, request, response, isHandled);
    }

    private void setName(HttpServletRequest request, String name, String accKey){
        int i = name.indexOf('?');
        if(i > 0){
            name = name.substring(0, i);
        }
        name = name.substring(accKey.length());

        if (JFinal.me().getConstants().getDevMode()){
            log.info("'三连击'自动选中下面路径后，连按两次'shift'键再'回车'会自动打开对应文件：\n"//
                    + name + ".json");
        }
        request.setAttribute(nameKey, name);
    }
}
